package com.hs.myshell.views;

import java.util.ArrayList;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.part.*;

import com.hs.myshell.EditorDialog;
import com.hs.myshell.action.EditTerminalSettingAction;
import com.hs.myshell.action.OpenTerminalAction;
import com.hs.myshell.data.SshSetting;
import com.hs.myshell.views.tree.TreeObject;
import com.hs.myshell.views.tree.TreeParent;

import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
import org.eclipse.core.runtime.IAdaptable;
import javax.inject.Inject;


/**
 * 这个自带的样例不好做局部刷新,下次改版用下面这个组件试一下
 * org.eclipse.jface.viewers.TreeViewerEditor
 * org.eclipse.swt.custom.TreeEditor
 * 
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class TreeView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "com.hs.myshell.views.TreeView";

	@Inject IWorkbench workbench;
	
	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action openTerminalAction;
	private Action newAction;
	private Action delAction;
	private Action editAction;
	private Action doubleClickAction;
	 
//	class TreeObject implements IAdaptable {
//		private String name;
//		private TreeParent parent;
//		
//		public TreeObject(String name) {
//			this.name = name;
//		}
//		public String getName() {
//			return name;
//		}
//		public void setParent(TreeParent parent) {
//			this.parent = parent;
//		}
//		public TreeParent getParent() {
//			return parent;
//		}
//		@Override
//		public String toString() {
//			return getName();
//		}
//		@Override
//		public <T> T getAdapter(Class<T> key) {
//			return null;
//		}
//	}
//	
//	class TreeParent extends TreeObject {
//		private ArrayList children;
//		public TreeParent(String name) {
//			super(name);
//			children = new ArrayList();
//		}
//		public void addChild(TreeObject child) {
//			children.add(child);
//			child.setParent(this);
//		}
//		public void removeChild(TreeObject child) {
//			children.remove(child);
//			child.setParent(null);
//		}
//		public TreeObject [] getChildren() {
//			return (TreeObject [])children.toArray(new TreeObject[children.size()]);
//		}
//		public boolean hasChildren() {
//			return children.size()>0;
//		}
//	}

	class ViewContentProvider implements ITreeContentProvider {
		private TreeParent invisibleRoot;
		private IViewSite site;

		public ViewContentProvider(IViewSite site) {
			super();
			this.site = site;
		}
		
		public Object[] getElements(Object parent) {
			if (parent.equals(this.site)) {
				if (invisibleRoot==null) initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}
		public Object getParent(Object child) {
			if (child instanceof TreeObject) {
				return ((TreeObject)child).getParent();
			}
			return null;
		}
		public Object [] getChildren(Object parent) {
			if (parent instanceof TreeParent) {
				return ((TreeParent)parent).getChildren();
			}
			return new Object[0];
		}
		public boolean hasChildren(Object parent) {
			if (parent instanceof TreeParent)
				return ((TreeParent)parent).hasChildren();
			return false;
		}
/*
 * We will set up a dummy model to initialize tree heararchy.
 * In a real code, you will connect to a real model and
 * expose its hierarchy.
 */
		private void initialize() {
			TreeObject to1 = new TreeObject("192.168.4.110");
			TreeObject to2 = new TreeObject("Leaf 2");
			TreeObject to3 = new TreeObject("Leaf 3");
			TreeParent p1 = new TreeParent("Parent 1");
			p1.addChild(to1);
			p1.addChild(to2);
			p1.addChild(to3);
			
			TreeObject to4 = new TreeObject("Leaf 4");
			TreeParent p2 = new TreeParent("Parent 2");
			p2.addChild(to4);
			
			TreeParent root = new TreeParent("Root");
			root.addChild(p1);
			root.addChild(p2);
			
			invisibleRoot = new TreeParent("会话组");
			invisibleRoot.addChild(root);
		}
	}

	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}
		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (obj instanceof TreeParent)
			   imageKey = ISharedImages.IMG_OBJ_FOLDER;
			return workbench.getSharedImages().getImage(imageKey);
		}
	}

	@Override
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		drillDownAdapter = new DrillDownAdapter(viewer);
		
	viewer.setContentProvider(new ViewContentProvider(getViewSite()));
	viewer.setInput(getViewSite());
	viewer.setLabelProvider(new ViewLabelProvider());

		// Create the help context id for the viewer's control
		workbench.getHelpSystem().setHelp(viewer.getControl(), "com.hs.myshell.viewer");
		getSite().setSelectionProvider(viewer);
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				TreeView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(openTerminalAction);
		manager.add(new Separator());
		manager.add(editAction);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(openTerminalAction);
		manager.add(new Separator());
		manager.add(newAction);
		manager.add(editAction);
		manager.add(delAction);
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(openTerminalAction);
		manager.add(editAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		openTerminalAction = new Action() {
			public void run() {
				//open selected terminal by node info
				//showMessage("Action 1 executed");
				IStructuredSelection selection = viewer.getStructuredSelection();
				Object obj = selection.getFirstElement();
//				showMessage("���� detected on "+obj.toString());
				
				new OpenTerminalAction(workbench.getActiveWorkbenchWindow(),selection).run();
			}
		};
		openTerminalAction.setText("连接");
		openTerminalAction.setToolTipText("Action 1 tooltip");
		openTerminalAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		editAction = new Action() {
			public void run() {
				IStructuredSelection selection = viewer.getStructuredSelection();
				TreeObject obj = (TreeObject)selection.getFirstElement();
				showMessage("Double-click detected on "+obj.toString());
				
				new EditorDialog(Display.getDefault().getActiveShell(),null,obj,viewer,getViewSite(),false).open();
				System.out.println("sout..........");
//				viewer.getContentProvider().inputChanged(viewer, selection, obj);
//				new EditTerminalSettingAction(workbench.getActiveWorkbenchWindow(),selection).run();
//				showMessage("Action 2 executed");
			}
		};
		editAction.setText("编辑");
		editAction.setToolTipText("Action 2 tooltip");
		editAction.setImageDescriptor(workbench.getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		newAction = new Action() {
			public void run() {
				IStructuredSelection selection = viewer.getStructuredSelection();
				TreeParent folder = (TreeParent)selection.getFirstElement();
//				showMessage("Double-click detected on "+folder.toString());
				
				new EditorDialog(Display.getDefault().getActiveShell(),folder,null,viewer,getViewSite(),true).open();
				System.out.println("sout..........");
//				viewer.getContentProvider().inputChanged(viewer, selection, obj);
//				new EditTerminalSettingAction(workbench.getActiveWorkbenchWindow(),selection).run();
//				showMessage("Action 2 executed");
			}
		};
		newAction.setText("新建");
		newAction.setToolTipText("Action 2 tooltip");
		newAction.setImageDescriptor(workbench.getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		delAction = new Action() {
			public void run() {
				boolean openConfirm = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),"提示", "确定删除");
				if(openConfirm) {
					IStructuredSelection selection = viewer.getStructuredSelection();
					TreeObject obj = (TreeObject)selection.getFirstElement();
					System.out.println(obj.getName());
					obj.getParent().removeChild(obj);
					viewer.refresh();
				}
			}
		};
		delAction.setText("删除");
		delAction.setToolTipText("Action 2 tooltip");
		delAction.setImageDescriptor(workbench.getSharedImages().
				getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		doubleClickAction = new Action() {
			public void run() {
				IStructuredSelection selection = viewer.getStructuredSelection();
				Object obj = selection.getFirstElement();
//				showMessage("Double-click detected on "+obj.toString());
				new EditTerminalSettingAction(workbench.getActiveWorkbenchWindow(),selection).run();
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Sample View",
			message);
	}

	@Override
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}
